package com.platform.user.service;

import com.platform.bean.JwtProperties;
import com.platform.user.entity.Admin;
import com.platform.user.entity.User;
import com.platform.utils.JwtTokenUtils;
import com.platform.utils.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class OnlineService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Resource
    private JwtProperties jwtProperties;

    public void saveAdmin(Admin admin, String token){
        String loginKey = jwtTokenUtils.loginUserKey(token);
        // jwtTokenUtils.getTokenPrefix(loginKey);
        redisUtils.set(loginKey, admin.getId().toString(), jwtProperties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
    }

    public void saveUser(User user, String token){
        String loginKey = jwtTokenUtils.loginUserKey(token);
        // jwtTokenUtils.getTokenPrefix(loginKey);
        redisUtils.set(loginKey, user.getId().toString(), jwtProperties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
    }

    public String queryOnlineAdminByAid(String aid) {
        String loginKey = jwtTokenUtils.loginUserKey(aid);
        return (String) redisUtils.get(loginKey);
    }

    public void kickOutAdminForAid(String aid) {
        String loginKey = jwtTokenUtils.loginUserKey(aid);
        redisUtils.del(loginKey);
    }

    public Long getPunishmentTtl(String username) {
        String punishmentKry = jwtTokenUtils.punishmentKey(username);
        return redisUtils.getExpireTtl(punishmentKry, TimeUnit.MILLISECONDS);
    }

    public void adminLogout(String token) {
        String loginKey = jwtTokenUtils.loginUserKey(token);
        redisUtils.del(loginKey);
    }
}
